package com.starblink.brand.model

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.google.gson.Gson
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.brand.bean.BrandMoreCardBean
import com.starblink.brand.bean.FilterCategoryBean
import com.starblink.brand.bean.FilterCategoryTitleBean
import com.starblink.brand.bean.FilterEndBean
import com.starblink.brand.bean.FilterPriceInputBean
import com.starblink.rocketreserver.FetchBrandCollectionDetailQuery
import com.starblink.rocketreserver.FetchBrandCollectionFrontCategoryListQuery
import com.starblink.rocketreserver.FetchBrandCollectionListRandomQuery
import com.starblink.rocketreserver.SearchProductsQuery
import com.starblink.rocketreserver.fragment.BrandCollectionInfoVoF
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.type.BrandCollectionDetailReq
import com.starblink.rocketreserver.type.BrandCollectionRandomReq
import com.starblink.rocketreserver.type.ProductQueryParam
import com.starblink.search.config.SearchConfig
import com.starblink.search.result.repository.model.GoodsResultEmptyModel
import kotlinx.coroutines.launch

class BrandCollectionVM : BaseViewModel() {

    val brandCollectionObserveData:ArrayList<Any> = ArrayList()//商品列表+推荐品牌集合
    val productList: MutableLiveData<ArrayList<Any>> = MutableLiveData(ArrayList())//记录当前页商品列表
    val brandRandomList=MutableLiveData<ArrayList<BrandMoreCardBean>>()//推荐的品牌列表
    val brandCollectionInfo=MutableLiveData<BrandCollectionInfoVoF>()//品牌信息

    val filterContentList: MutableLiveData<ArrayList<Any>> = MutableLiveData(ArrayList()) //筛选弹框 adapter集合
    val filterPriceInputBean = FilterPriceInputBean() //价格筛选
    val filterCategoryList = ArrayList<FilterCategoryBean>() //一级类目筛选
    val filterCategoryListResult = MutableLiveData<String>() //一级类目筛选
    val filterLetterList:MutableLiveData<ArrayList<FilterCategoryTitleBean>> = MutableLiveData(ArrayList()) //A B C ..
    private val emptyModel: GoodsResultEmptyModel by lazyOnNone {
        GoodsResultEmptyModel(emptyTxt2 = "No products is found.")
    }
    var letterList=listOf(
    FilterCategoryTitleBean('A'), FilterCategoryTitleBean('B'),FilterCategoryTitleBean('C'),FilterCategoryTitleBean('D')
    ,FilterCategoryTitleBean('E'), FilterCategoryTitleBean('F'), FilterCategoryTitleBean('G'), FilterCategoryTitleBean('H'),
    FilterCategoryTitleBean('I'), FilterCategoryTitleBean('J'), FilterCategoryTitleBean('K'), FilterCategoryTitleBean('L'),
    FilterCategoryTitleBean('M'), FilterCategoryTitleBean('N'), FilterCategoryTitleBean('O'), FilterCategoryTitleBean('P'),
    FilterCategoryTitleBean('Q'), FilterCategoryTitleBean('R'), FilterCategoryTitleBean('S'), FilterCategoryTitleBean('T'),
    FilterCategoryTitleBean('U'), FilterCategoryTitleBean('V'), FilterCategoryTitleBean('W'), FilterCategoryTitleBean('X'),
    FilterCategoryTitleBean('Y'), FilterCategoryTitleBean('Z'), FilterCategoryTitleBean('#') )

    var pageNo = 1
    var hasNext=true //是否有下一页

    var sortType= SearchConfig.SORT_DEFAULT //排序方式
    var lowestPrice:Double?=null//最低价格
    var highestPrice:Double?=null//最高价格
    var frontCategoryIds:ArrayList<String>?=null//一级类目id
    private val gson= Gson()
    /**
     * 查询品牌集详情
     * brandCollectionId 品牌集 id
     * productId 首页品牌集展示图片所属商品的 id, 用于后续页面置顶
     * initData 是否刷新数据
     */
    fun reqBrandDetailData(brandCollectionId:String?,productId:String?,initData: Boolean = true,ifShowLoading:Boolean=false){
        if (initData) {
            pageNo = 1
        }else{
            pageNo++
        }
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchBrandCollectionDetailQuery(
                    params = BrandCollectionDetailReq(
                        brandCollectionId = brandCollectionId?:"",
                        productId=productId?:"",
                        pageNo = pageNo,
                        pageSize = 20,
                        sortType = Optional.present(sortType),
                        lowestPrice = Optional.present(lowestPrice),
                        highestPrice = Optional.present(highestPrice),
                        foregroundCategoryIds = Optional.present(frontCategoryIds),
                    ),
                    //1.4.0版本 需求将2改成了1
                    type = Optional.present(1) //brotherOffer字段 加个入参 type =2
                ), showDefaultLoading = ifShowLoading
            )
            //当前页面商品重置
            productList.value?.clear()
            if (initData) {
                brandCollectionObserveData.clear()
            }

            response?.data?.fetchBrandCollectionDetail?.let { it ->
                //品牌信息
                it.brandCollectionInfo?.brandCollectionInfoVoF.let {brandInfo-> brandCollectionInfo.value=brandInfo }

                //商品列表
                hasNext= it.hasNext

                it.productList?.mapIndexedNotNull { index, item ->
                    gson.fromJson(item?.productB?.toJson(),ProductF::class.java)
                }
                ?.apply {
                    productList.value?.addAll(this)
                }
                if(it.recommendFail){
                    toast("Internet jammed, please reload")
                }
            }
            if(response?.data?.fetchBrandCollectionDetail==null){
                //接口异常 兜底
                hasNext=false
            }
            //判断是否有下一页 进行推荐品牌的接口请求
            if(!hasNext) {
                if(brandCollectionObserveData.isEmpty()&&productList.value?.isEmpty()==true){
                    //商品列表为空
                    brandCollectionObserveData.add(emptyModel)
                }

                reqRandomBrandList(brandCollectionId)
            }

            productList.postValue(productList.value)

            //测试数据
//            reqTestBrandDetailData(initData,ifShowLoading)
        }
    }
    fun reqTestBrandDetailData(initData: Boolean = true,ifShowLoading:Boolean=false){
        if (initData) {
            pageNo = 1
        }else{
            pageNo++
        }
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                SearchProductsQuery(
                    params = ProductQueryParam(
                        contentSearch = "nick",
                        searchScene = Optional.present(1),
                        sortType = 0.optional(),
                        saleableCountryFlag = true.optional(),
                        pageNo = pageNo,
                        pageSize = 20,//pageSize不能随意改动，adapter根据长度自动加载更多
                    )
                ), showDefaultLoading = ifShowLoading
            )
            response?.data?.searchGoodsV4?.productList?.let { it ->
                Log.e("reqBrandData", "-----${it.size}")
                val list = it.mapNotNull { it?.productF }
                if (initData) {
                    brandCollectionObserveData?.clear()
                }
                //测试第3页为最后一页
                hasNext= pageNo<=2

                productList.value?.clear()
                productList.value?.addAll(list)

                productList.postValue(productList.value)

                //判断是否有下一页 进行推荐品牌的接口请求
                if(!hasNext) {
                    reqRandomBrandList("")
                }
            }
        }
    }

    /**
     * 查询随机个品牌集
     * brandCollectionId: 当前品牌集 id
     */
    private fun reqRandomBrandList(brandCollectionId:String?){
        //请求接口
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchBrandCollectionListRandomQuery(
                    params = BrandCollectionRandomReq(
                        brandCollectionId =brandCollectionId?:"",
                        size = Optional.present(5),
                    )
                ), showDefaultLoading = false
            )
            response?.data?.fetchBrandCollectionListRandom?.let {brandCollectionList->
                val brandList = ArrayList<BrandMoreCardBean>()
                if(brandCollectionList.isNotEmpty()) {
                    brandCollectionList.mapIndexedNotNull { index, it ->
                        brandList.add(BrandMoreCardBean(index, it?.brandCollectionInfoVoF))
                    }
                }
                brandRandomList.value = brandList
            }

            if(response?.data?.fetchBrandCollectionListRandom==null){
                //接口异常兜底
                brandRandomList.postValue(ArrayList())
            }
            //测试
//            reqTestRandomBrandList()
        }
    }

    /**
     * 测试推荐品牌数据
     */
    private fun reqTestRandomBrandList(){

        //没有更多商品时添加推荐品牌
        //测试展示推荐其它品牌
        val brandRandomList=ArrayList<BrandMoreCardBean>()
        brandRandomList.add(BrandMoreCardBean(0,BrandCollectionInfoVoF("","","barndName","70",10000,"","https://test-kproject-oss.starblink.co/klarna_goods/underarmour/f78a10762574014300a0fa62bedee677.jpg")))
        brandRandomList.add(BrandMoreCardBean(1,BrandCollectionInfoVoF("","","barndName","50",100,"","https://www.pricerunner.com/product/640x640/3001984699/Blomus-Modo-Wall-Shelf-51cm.jpg")))
        brandRandomList.add(BrandMoreCardBean(2,BrandCollectionInfoVoF("","","barndName","40",120,"","https://www.pricerunner.se/images/152x40/logos/Pinewood.jpg")))
        brandRandomList.add(BrandMoreCardBean(3,BrandCollectionInfoVoF("","","barndName","50",1000,"","https://test-kproject-oss.starblink.co/klarna_goods/farfetch_all/a3318448d0675b299faef13a4ea978d8.jpg")))
        brandRandomList.add(BrandMoreCardBean(4,BrandCollectionInfoVoF("","","barndName","60",104,"","https://test-kproject-oss.starblink.co/klarna_goods/underarmour/bc3b6f6893e21f595d63fc797c7ff6f6.jpg")))
        this.brandRandomList.value=brandRandomList
    }

    fun initFilterPriceDate(lowestPrice:Double?=null, highestPrice:Double?=null){
        filterContentList.value!!.add(filterPriceInputBean)
        setFilterPriceDate(lowestPrice,highestPrice)
    }
    fun setFilterPriceDate(lowestPrice:Double?=null, highestPrice:Double?=null){
        filterPriceInputBean.min=lowestPrice
        filterPriceInputBean.max=highestPrice
        filterContentList.postValue(filterContentList.value)
    }

    //修改字母状态
    fun changeLetterState(firstPosition:Int,lastPosition:Int){
//        var firstItem= filterContentList.value!![firstPosition]
//        var lastItem= filterContentList.value!![lastPosition]
//        var firstChat='#'
//        var lastChat='#'
//        if(firstItem is FilterCategoryBean){
//            firstChat=firstItem.key
//        }else if(firstItem is FilterCategoryTitleBean){
//            firstChat=firstItem.key
//        }
//        if(lastItem is FilterCategoryBean){
//            lastChat=lastItem.key
//        }else if(lastItem is FilterCategoryTitleBean){
//            lastChat=lastItem.key
//        }
//        filterLetterList.value!!.map {
//            val itemKey=if(it.key=='#') '[' else it.key // # ASCII值转成比z大的
//            val firstKey=if(firstChat=='#') '[' else firstChat // # ASCII值转成比z大的
//            val lastKey=if(lastChat=='#') '[' else lastChat // # ASCII值转成比z大的
//            it.ifChecked = (itemKey.code>=firstKey.code&&itemKey.code<=lastKey.code)
//        }

        filterLetterList.value!!.map {
            it.ifChecked = false
        }
        for(position in firstPosition..lastPosition){
            var item= filterContentList.value!![position]
            var itemChat:Char?=null
            if(item is FilterCategoryBean){
                itemChat=item.key
            }else if(item is FilterCategoryTitleBean){
                itemChat=item.key
            }
            itemChat?.let {chatItem->
                filterLetterList.value!!.map {letter->
                     if(chatItem.code==letter.key.code){
                         letter.ifChecked=true
                     }
                }
            }
        }

        filterLetterList.postValue(filterLetterList.value)
    }

    /**
     * 获取一级分类数据
     * brandCollectionId 当前的品牌集合id
     * frontCategoryIds 已选中的分类
    **/
    fun getFilterCategoryData(brandCollectionId:String,frontCategoryIds:ArrayList<String>?=null){
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchBrandCollectionFrontCategoryListQuery(
                    brandCollectionId =brandCollectionId
                ), showDefaultLoading = false
            )
            response?.data?.fetchBrandCollectionFrontCategoryList?.let { categoryList ->
                categoryList.forEach {
                    var categoryF=it?.categoryF
                    var key=categoryF?.name?.uppercase()?.toCharArray()?.get(0)?:'#'
                    if(key.code<'A'.code||key.code>'Z'.code){
                        key='#'
                    }
                    filterCategoryList.add(FilterCategoryBean(key = key,ifChecked=frontCategoryIds?.contains(categoryF?.id.toString())==true, categoryF=categoryF))
                }

                //归类
                letterList.forEach {letterItem->
                    filterContentList.value!!.add(FilterCategoryTitleBean(letterItem.key))
                    filterCategoryList.forEach {item->
                        if(letterItem.key.code== item.key.code){
                            filterContentList.value!!.add(item)
                        }
                    }
                    //最后一个是title说明该分类无内容 删除该类
                    if(filterContentList.value!!.last() is FilterCategoryTitleBean){
                        filterContentList.value!!.removeLast()
                    }
                }
                filterContentList.value!!.add(FilterEndBean())
                filterContentList.postValue(filterContentList.value)
                filterCategoryListResult.postValue("")
            }

            //测试
//            getTestFilterCategoryData(frontCategoryIds)
        }
    }

    //测试数据--- 一级类目
    fun getTestFilterCategoryData(frontCategoryIds:ArrayList<String>?){
//        filterCategoryList.add(FilterCategoryBean('A',false,CategoryF("1","A BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('A',false,CategoryF("2","A BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('B',false,CategoryF("3","B BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('B',false,CategoryF("4","B BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('C',false,CategoryF("5","C BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('C',false,CategoryF("6","C BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('D',false,CategoryF("7","D BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('D',false,CategoryF("8","D BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('E',false,CategoryF("9","E BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('E',false,CategoryF("10","E BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('F',false,CategoryF("11","F BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('F',false,CategoryF("12","F BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('G',false,CategoryF("13","G BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('G',false,CategoryF("14","G BrandName",0,"","",false,"","","")))
//        filterCategoryList.add(FilterCategoryBean('#',false,CategoryF("15","# BrandName",0,"","",false,"","","")))

        //设置选中的item
        frontCategoryIds?.let {
            filterCategoryList.forEach {item->
                if(frontCategoryIds.contains(item.categoryF?.id)){
                    item.ifChecked=true
                }
            }
        }

        //A~#
//        val matLetterList:MutableList<FilterCategoryTitleBean> = mutableListOf()
        //归类
        letterList.forEach {letterItem->
            filterContentList.value!!.add(FilterCategoryTitleBean(letterItem.key))
//            matLetterList.add(FilterCategoryTitleBean(letterItem.key))
            filterCategoryList.forEach {item->
                if(letterItem.key.code== item.key.code){
                    filterContentList.value!!.add(item)
                }
            }
            if(filterContentList.value!!.last() is FilterCategoryTitleBean){
                filterContentList.value!!.removeLast()
//                matLetterList.removeLast()
            }
        }
        filterContentList.value!!.add(FilterEndBean())
        filterContentList.postValue(filterContentList.value)

        //A~#
//        filterLetterList.value!!.addAll(matLetterList)
//        filterLetterList.postValue(filterLetterList.value)
    }

    //A~# 全部展示
    fun getFilterLetter(){
        var matLetterList:MutableList<FilterCategoryTitleBean> = mutableListOf()
        letterList.map {
            matLetterList.add(it)
        }
        filterLetterList.value!!.addAll(matLetterList)
        filterLetterList.postValue(filterLetterList.value)
    }
}